# -*- coding:utf-8 -*-
# @Time:2024/4/1921:01
# @Author:miuzg
# @FileName:new test2.py
# @Software:PyCharm

import time
from multiprocessing import Process, Queue


def get_time(fun):
    def calc_time(*args, **kwargs):
        start_time = time.time()
        res = fun(*args, **kwargs)
        end_time = time.time()
        print('执行时间为', end_time - start_time)
        return res

    return calc_time


# 判断是否为质数
def work(num):
    if num < 2:
        return False
    for i in range(2, num):
        if num % i == 0:
            return False
    return True


class KeyProcess(Process):
    # begin：起点，end：终点
    def __init__(self, begin, end, q):
        super(KeyProcess, self).__init__()
        self.begin = begin
        self.end = end
        self.q = q

    def run(self) -> None:
        total = 0
        for i in range(self.begin, self.end):
            if work(i):
                total += i
        self.q.put(total)


@get_time
def miuzg(q):
    process = []
    for i in range(1, 100001, 25000):
        p = KeyProcess(i, min(i + 25000, 100001), q)# 这样写更安全
        process.append(p)
        p.start()

    for p in process:
        p.join()

    # 结束信号
    q.put(None)


if __name__ == '__main__':
    q = Queue()
    miuzg(q)

    total_sum = 0
    while 1:
        res = q.get()
        if res is None:  # 接收到结束信号就停止
            break
        total_sum += res
    print('1到100000的质数和为', total_sum)
